<template>
<div class="uni-gsarea-map">
  <el-dialog
    :title="title"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :visible.sync="visible">
    <el-form :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"  :disabled="method==='view'"
             label-width="120px">
      <el-row  :gutter="15">
        <el-col :span="12">
            <el-form-item label="名称" prop="name"
                :rules="[
                  {required: true, message:'名称不能为空', trigger:'blur'}
                 ]">
			        <el-input v-model="inputForm.name" placeholder="请填写名称"     ></el-input>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="排序" prop="sort"
                :rules="[
                  {required: true, message:'排序不能为空', trigger:'blur'},
                  {validator: validator.isNumber, trigger:'blur'}
                 ]">
			        <el-input v-model="inputForm.sort" placeholder="请填写排序"     ></el-input>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="车间ID" prop="chejianId"
                :rules="[
                  {required: true, message:'车间ID不能为空', trigger:'blur'}
                 ]">
              <el-input v-model="inputForm.chejianId" placeholder="请填写车间ID"     ></el-input>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="车间名称" prop="chejianName"
                :rules="[
                  {required: true, message:'车间名称不能为空', trigger:'blur'}
                 ]">
              <el-input v-model="inputForm.chejianName" placeholder="请填写车间名称"     ></el-input>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="工段ID" prop="gongduanId"
                :rules="[
                  {required: true, message:'工段ID不能为空', trigger:'blur'}
                 ]">
              <el-input v-model="inputForm.gongduanId" placeholder="请填写工段ID"     ></el-input>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="工段名称" prop="gongduanName"
                :rules="[
                  {required: true, message:'工段名称不能为空', trigger:'blur'}
                 ]">
              <el-input v-model="inputForm.gongduanName" placeholder="请填写工段名称"     ></el-input>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="区域ID" prop="quyuId"
                :rules="[
                 ]">
              <el-input v-model="inputForm.quyuId" placeholder="请填写区域ID"     ></el-input>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="区域名称" prop="quyuName"
                :rules="[
                 ]">
              <el-input v-model="inputForm.quyuName" placeholder="请填写区域名称"     ></el-input>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="楼层ID" prop="floorId"
                :rules="[
                 ]">
              <el-input v-model="inputForm.floorId" placeholder="请填写楼层ID"     ></el-input>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="楼层名称" prop="floorName"
                :rules="[
                 ]">
              <el-input v-model="inputForm.floorName" placeholder="请填写楼层名称"     ></el-input>
           </el-form-item>
        </el-col>

        <el-col :span="12">
            <el-form-item label="区域类型" prop="areaType"
                :rules="[
                  {required: true, message:'区域类型不能为空', trigger:'blur'}
                 ]">
		            <el-select v-model="inputForm.areaType" placeholder="请选择"  style="width: 100%;" @change="inputForm.areaInfo=''">
                          <el-option
                            v-for="item in $dictUtils.getDictList('lora_fence_area')"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                          </el-option>
                      </el-select>
           </el-form-item>
        </el-col>
        <el-col :span="12" v-if="inputForm.areaType ==='整栋建筑'">
          <el-form-item label="选择建筑" prop="areaInfo" :rules="[
            {required: true, message:'建筑不能为空', trigger:'blur'}
            ]">
            <el-select v-model="inputForm.areaInfo" placeholder="请选择建筑" style="width: 100%;">
              <el-option v-for="item in buildingList" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-else-if="inputForm.areaType ==='单个楼层'">
          <el-form-item label="选择楼层" prop="areaInfo"
              :rules="[
                {required: true, message:'楼层不能为空', trigger:'blur'}
               ]">
            <SelectTree
              ref="floor"
              placeholder="请选择楼层"
              :props="{
                  value: 'id',             // ID字段名
                  label: 'showName',         // 显示名称
                  children: 'childNodes'    // 子级字段名
                }"
              url="/smis/floor/jfFloor/treeData"
              :value="inputForm.areaInfo"
              :clearable="true"
              :accordion="true" @getValue="(val)=>{inputForm.areaInfo = val||'';}"/>
          </el-form-item>
        </el-col>
        <template v-else-if="inputForm.areaType ==='自定义区域'">
          <el-col :span="12">
            <el-form-item label="选择楼层" prop="areaFloorId" :rules="[
                {required: true, message:'楼层不能为空', trigger:'blur'}
               ]">
              <SelectTree ref="floor" placeholder="请选择楼层" :props="{
                  value: 'id',             // ID字段名
                  label: 'showName',         // 显示名称
                  children: 'childNodes'    // 子级字段名
                }" url="/smis/floor/jfFloor/treeData" :value="inputForm.areaFloorId" :clearable="true" :accordion="true"
                @getValue="floorChange" />
            </el-form-item>
          </el-col>
          <el-col :span="24" style="height: 400px;">
            <el-form-item label="区域绘制" prop="areaInfo" :rules="[
                  {required: true, message:'请绘制区域', trigger:'blur'}
                 ]">
              <FenceMap ref="fenceMap"></FenceMap>
            </el-form-item>
          </el-col>
        </template>
       <!-- <el-col :span="12">
            <el-form-item label="区域信息" prop="areaInfo"
                :rules="[
                  {required: true, message:'区域信息不能为空', trigger:'blur'}
                 ]">
			        <el-input v-model="inputForm.areaInfo" placeholder="请填写区域信息"     ></el-input>
           </el-form-item>
        </el-col> -->
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">关闭</el-button>
      <el-button type="primary" v-if="method != 'view'" @click="doSubmit()" v-noMoreClick>确定</el-button>
    </span>
  </el-dialog>
</div>
</template>

<script>
  import SelectTree from '@/components/treeSelect/treeSelect.vue'
  import FenceMap from '@/components/jfMap/fenceMap.vue'
  export default {
    data () {
      return {
        title: '',
        method: '',
        visible: false,
        loading: false,
        inputForm: {
          id: '',
          parent: {
            id: ''
          },
          name: '',
          sort: '',
          areaType: '',
          areaFloorId: '',
          areaInfo: '',
          chejianId: '',
          chejianName: '',
          gongduanId: '',
          gongduanName: '',
          quyuId: '',
          quyuName: '',
          floorId: '',
          floorName: '',
          dataType: ''
        }
      }
    },
    components: {
      SelectTree,
      FenceMap
    },
    computed: {
      buildingList: {
        get() {
          return this.$store.state.shopdata.buildingList
        }
      }
    },
    // inputForm.areaType ==='自定义区域'
    methods: {
      init (method, obj) {
        this.method = method
        this.inputForm.id = obj.id
        if (method === 'add') {
          this.title = '新建工段'
        } else if (method === 'addChild') {
          this.title = '新建区域'
        } else if (method === 'edit') {
          this.title = '修改'
        } else if (method === 'view') {
          this.title = '查看'
        }
        this.visible = true
        this.loading = false
        this.$nextTick(() => {
          this.$refs.inputForm.resetFields()
          this.inputForm.parent.id = obj.parent.id
          this.inputForm.parent.name = obj.parent.name
          this.inputForm.dataType = method === 'add' ? '工段':'区域';
          if (method === 'edit' || method === 'view') { // 修改或者查看
            this.loading = true
            this.$http({
              url: `/lora/area/jfLoraGsArea/queryById?id=${this.inputForm.id}`,
              method: 'get'
            }).then(({data}) => {
              this.inputForm = this.recover(this.inputForm, data.jfLoraGsArea)
              if(this.inputForm.parent.id === '0') {
                if (method === 'edit') {
                  this.title = '修改工段'
                } else if (method === 'view') {
                  this.title = '查看工段'
                }
              } else {
                if (method === 'edit') {
                  this.title = '修改区域'
                } else if (method === 'view') {
                  this.title = '查看区域'
                }
              }
              this.loading = false
              setTimeout(()=>{
                if(this.$refs.fenceMap) {
                  if(this.inputForm.areaType === '自定义区域') {
                    this.$refs.fenceMap.showFloor(this.inputForm.areaFloorId)
                    this.$refs.fenceMap.setDrawJson(this.inputForm.areaInfo)
                  } else {
                    this.$refs.fenceMap.clearDraw()
                  }
                }
              }, 500)
            })
          } else {
            if(this.$refs.fenceMap) {
              this.$refs.fenceMap.clearDraw()
            }
          }
          if(this.$refs.fenceMap) {
            this.$refs.fenceMap.resize();
          }
        })
      },
      // 表单提交
      doSubmit () {
        if(this.inputForm.areaType =='自定义区域') {
           this.inputForm.areaInfo = JSON.stringify(this.$refs.fenceMap.getDrawJson());
        }
        this.$refs['inputForm'].validate((valid) => {
          if (valid) {
            this.loading = true
            this.$http({
              url: `/lora/area/jfLoraGsArea/save`,
              method: 'post',
              data: this.inputForm
            }).then(({data}) => {
              if (data && data.success) {
                this.visible = false
                this.$message.success(data.msg)
                this.$emit('refreshDataList')
              }
              this.loading = false
            })
          }
        })
      },
      floorChange(value) {
        if (value && value != '') {
          this.inputForm.areaFloorId = value;
          this.$refs.fenceMap.showFloor(value);
        }
      },
      // endDraw(points) {
      //   if (points) {
      //     var infoJson = {
      //       floorId: this.inputForm.areaFloorId,
      //       points: points
      //     }
      //     this.inputForm.areaInfo = JSON.stringify(infoJson)
      //   } else {
      //     this.inputForm.areaInfo = ''
      //   }
      // },
      /**
       * 检测目标点是否进入电子围栏区域
       * @param {Array} checkPoint - 校验坐标
       * @param {Array} polygonPoints - 形成电子围栏的坐标
       * @returns {Boolean} true 或 false
       * @description 此方法仅判断处于同一个平面的目标点是否在区域内（只判断坐标x和z值），
       *     不考虑两者当前离地高度（坐标的y值）
       */
      // isInPolygon(checkPoint, polygonPoints) {
      //   var counter = 0;
      //   var i;
      //   var xinters;
      //   var p1, p2;
      //   var pointCount = polygonPoints.length;
      //   p1 = polygonPoints[0];
      //   for (i = 1; i <= pointCount; i++) {
      //     p2 = polygonPoints[i % pointCount];
      //     if (checkPoint.x > Math.min(p1.x, p2.x) && checkPoint.x <= Math.max(p1.x, p2.x)) {
      //       if (checkPoint.y <= Math.max(p1.y, p2.y)) {
      //         if (p1.x != p2.x) {
      //           xinters = (checkPoint.x - p1.x) * (p2.y - p1.y) / (p2.x - p1.x) + p1.y;
      //           if (p1.y == p2.y || checkPoint.y <= xinters) {
      //             counter++;
      //           }
      //         }
      //       }
      //     }
      //     p1 = p2;
      //   }
      //   if (counter % 2 == 0) {
      //     return false;
      //   } else {
      //     return true;
      //   }
      // }
    }
  }
</script>
<style lang="less">
  .uni-gsarea-map {
    .el-dialog__body {
      height: 100%;
      position: relative;
      overflow: hidden;
    }
  }
</style>
